"""
使用示例 - 演示如何通过代码使用中央空调系统
"""
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from core.central_ac import CentralAC
from core import config
import time


def example_basic_usage():
    """基础使用示例"""
    print("=" * 60)
    print("示例1: 基础使用")
    print("=" * 60)
    
    # 创建中央空调实例
    ac = CentralAC(total_rooms=5, max_service_objects=2)
    ac.start()
    
    # 模拟房间001发送请求
    print("\n房间001: 请求制冷到22度，高风")
    result = ac.handle_request("001", 22, config.WIND_SPEED_HIGH, config.MODE_COOLING)
    print(f"结果: {result['message']}")
    
    # 查看房间状态
    time.sleep(2)
    state = ac.get_room_state("001")
    print(f"当前温度: {state['current_temp']}°C")
    print(f"目标温度: {state['target_temp']}°C")
    print(f"服务状态: {'服务中' if state['is_serving'] else '等待中' if state['is_waiting'] else '待机'}")
    
    # 关机
    time.sleep(3)
    print("\n房间001: 关机")
    ac.turn_off("001")
    
    ac.stop()
    print("\n示例1完成\n")


def example_scheduling():
    """调度策略示例"""
    print("=" * 60)
    print("示例2: 调度策略演示")
    print("=" * 60)
    
    # 创建中央空调实例（最多2个服务对象）
    ac = CentralAC(total_rooms=5, max_service_objects=2)
    ac.start()
    
    # 房间001和002都请求服务（低风）
    print("\n房间001: 请求制冷到20度，低风")
    result1 = ac.handle_request("001", 20, config.WIND_SPEED_LOW, config.MODE_COOLING)
    print(f"结果: {result1['message']}")
    
    time.sleep(1)
    
    print("\n房间002: 请求制冷到21度，低风")
    result2 = ac.handle_request("002", 21, config.WIND_SPEED_LOW, config.MODE_COOLING)
    print(f"结果: {result2['message']}")
    
    time.sleep(2)
    
    # 房间003请求高风（优先级高，应该抢占服务）
    print("\n房间003: 请求制冷到19度，高风（优先级高）")
    result3 = ac.handle_request("003", 19, config.WIND_SPEED_HIGH, config.MODE_COOLING)
    print(f"结果: {result3['message']}")
    
    # 查看监控信息
    time.sleep(1)
    print("\n当前系统状态:")
    info = ac.get_monitoring_info()
    
    print("\n服务队列:")
    for service in info['service_queue']:
        print(f"  房间{service['room_id']}: 风速={service['wind_speed']}, "
              f"服务时长={service['service_duration']}秒")
    
    print("\n等待队列:")
    for waiting in info['waiting_queue']:
        print(f"  房间{waiting['room_id']}: 风速={waiting['wind_speed']}, "
              f"已等待={waiting['waiting_duration']:.1f}秒")
    
    # 清理
    time.sleep(3)
    ac.turn_off("001")
    ac.turn_off("002")
    ac.turn_off("003")
    ac.stop()
    print("\n示例2完成\n")


def example_billing():
    """账单系统示例"""
    print("=" * 60)
    print("示例3: 账单和统计")
    print("=" * 60)
    
    from core.billing import BillingManager
    from core.statistics import StatisticsReport
    
    # 创建中央空调实例
    ac = CentralAC(total_rooms=5, max_service_objects=2)
    ac.start()
    
    # 模拟使用
    print("\n房间001: 开始使用空调")
    ac.handle_request("001", 22, config.WIND_SPEED_HIGH, config.MODE_COOLING)
    time.sleep(5)  # 使用5秒
    
    print("房间001: 更改为中风")
    ac.handle_request("001", 22, config.WIND_SPEED_MEDIUM, config.MODE_COOLING)
    time.sleep(5)  # 再使用5秒
    
    print("房间001: 关机")
    ac.turn_off("001")
    
    # 生成账单
    print("\n生成账单:")
    room_state = ac.room_states["001"]
    bill = BillingManager.generate_bill(room_state)
    details = BillingManager.generate_detail_list(room_state)
    
    print(f"房间号: {bill['room_id']}")
    print(f"总耗电量: {bill['total_power_consumption']} 度")
    print(f"总费用: ¥{bill['total_cost']} 元")
    print(f"详单数量: {bill['detail_count']} 条")
    
    print("\n详单列表:")
    for detail in details:
        print(f"  #{detail['serial_number']}: "
              f"风速={detail['wind_speed']}, "
              f"时长={detail['duration_minutes']:.2f}分钟, "
              f"费用=¥{detail['cost']:.2f}")
    
    # 生成统计报表
    print("\n生成统计报表:")
    report = StatisticsReport.generate_report(ac.room_states)
    print(f"使用房间数: {report['summary']['total_rooms_used']}")
    print(f"总费用: ¥{report['summary']['total_cost']} 元")
    
    ac.stop()
    print("\n示例3完成\n")


def main():
    """运行所有示例"""
    print("\n" + "=" * 60)
    print("中央温控系统 - 使用示例")
    print("=" * 60 + "\n")
    
    try:
        # 运行示例1
        example_basic_usage()
        
        # 运行示例2
        example_scheduling()
        
        # 运行示例3
        example_billing()
        
        print("=" * 60)
        print("所有示例运行完成!")
        print("=" * 60)
        
    except KeyboardInterrupt:
        print("\n\n示例被用户中断")
    except Exception as e:
        print(f"\n运行示例时出错: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()

